import React from "react"
import UserListStore from "./UserListStore"

const { createContext, useContext } = React

// 1、总的RootStore，在构造函数里面添加子Store作为成员
// 1.1、注意初始化Store，如果服务端传递过来了数据，用该数据初始化
class RootStore {
  constructor() {
    const initialStore = typeof window !=="undefined" && window.INITIAL_STATE
    const users = initialStore && initialStore.userListStore.users
    
    this.userListStore = new UserListStore(users)
  }
}

// 2、通过context方式将rootStore传递给子元素
// 2.1、导出Provider给入口
// 2.2、导出Store给组件
export const rootStore = new RootStore()
const RootStoreContext  = createContext()
export const RootStoreProvider = ({ children }) => {
  return (
    <RootStoreContext.Provider value={rootStore}>
      {children}
    </RootStoreContext.Provider>
  )
}
export const useRootStore = () => {
  return useContext(RootStoreContext)
}
